package com.likuicat.picture_ddd.application.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.likuicat.picture_ddd.domain.space.service.SpaceDomainService;
import com.likuicat.picture_ddd.infrastructure.exception.BusinessException;
import com.likuicat.picture_ddd.infrastructure.exception.ErrorCode;
import com.likuicat.picture_ddd.infrastructure.exception.ThrowUtils;
import com.likuicat.picture_ddd.infrastructure.mapper.SpaceMapper;
import com.likuicat.picture_ddd.interfaces.dto.space.SpaceAddRequest;
import com.likuicat.picture_ddd.interfaces.dto.space.SpaceQueryRequest;
import com.likuicat.picture_ddd.domain.space.entity.Space;
import com.likuicat.picture_ddd.domain.space.entity.SpaceUser;
import com.likuicat.picture_ddd.domain.user.entity.User;
import com.likuicat.picture_ddd.domain.space.valueobject.SpaceLevelEnum;
import com.likuicat.picture_ddd.domain.space.valueobject.SpaceRoleEnum;
import com.likuicat.picture_ddd.domain.space.valueobject.SpaceTypeEnum;
import com.likuicat.picture_ddd.interfaces.vo.space.SpaceVO;
import com.likuicat.picture_ddd.application.service.SpaceApplicationService;
import com.likuicat.picture_ddd.application.service.SpaceUserApplicationService;
import com.likuicat.picture_ddd.application.service.UserApplicationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;


/**
 * @author fc3379757631
 * @description 针对表【space(空间)】的数据库操作Service实现
 * @createDate 2025-05-06 16:38:48
 */
@Service
@Slf4j
public class SpaceApplicationServiceImpl extends ServiceImpl<SpaceMapper, Space>
        implements SpaceApplicationService {

    @Resource
    private SpaceDomainService spaceDomainService;

    @Resource
    private UserApplicationService userApplicationService;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    @Lazy //延迟注入，解决循环依赖
    private SpaceUserApplicationService spaceUserApplicationService;

    //关闭分库分表
//    @Resource
//    @Lazy
//    private DynamicShardingManager dynamicShardingManager;

    //使用ConcurrentHashMap存储锁对象
    Map<Long,Object> lockMap = new ConcurrentHashMap<>();

    /**
     * 转化为QueryWrapper
     * @param spaceQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
        return  spaceDomainService.getQueryWrapper(spaceQueryRequest);
    }

    @Override
    public SpaceVO getSpaceVO(Space space, HttpServletRequest request) {
        SpaceVO spaceVO = SpaceVO.objToVo(space);
        Long userId = space.getUserId();
        if (userId != null && userId > 0) {
            User user = userApplicationService.getUserById(userId);
            if (user != null) {
                spaceVO.setUser(userApplicationService.getUserToUserVO(user));
            }
        }
        return spaceVO;
    }

    @Override
    public Page<SpaceVO> getSpaceVOPage(Page<Space> spacePage, HttpServletRequest request) {
        List<Space> records = spacePage.getRecords();
        //创建Page<SpaceVO>对象
        Page<SpaceVO> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(), spacePage.getTotal());
        if (CollUtil.isEmpty(records)) {
            return spaceVOPage;
        }
        //使用stream流转化
        List<SpaceVO> spaceVOList = records.stream().map(SpaceVO::objToVo).collect(Collectors.toList());
        //取出userId集合
        Set<Long> collect = spaceVOList.stream().map(SpaceVO::getUserId).collect(Collectors.toSet());
        //查询所有user集合,只发送一次请求，查询所有，效率更高
        Map<Long, List<User>> listMap = userApplicationService.listByIds(collect).stream().collect(Collectors.groupingBy(User::getId));
        for (SpaceVO spaceVO : spaceVOList) {
            Long userId = spaceVO.getUserId();
            User user = null;
            if (listMap.containsKey(userId)) {
                user = listMap.get(userId).get(0);
            }
            spaceVO.setUser(userApplicationService.getUserToUserVO(user));
        }
        spaceVOPage.setRecords(spaceVOList);
        return spaceVOPage;
    }


    @Override
    public void fillSpaceBySpaceLevel(Space space) {
        spaceDomainService.fillSpaceBySpaceLevel(space);
    }

    @Override
    public long addSpace(SpaceAddRequest spaceAddRequest, User loginUser) {
        ThrowUtils.throwIf(spaceAddRequest == null, ErrorCode.NOT_FOUND_ERROR);
        //1.填充参数默认值
        String spaceName = spaceAddRequest.getSpaceName();
        if(StrUtil.isBlank(spaceName)){
            spaceAddRequest.setSpaceName("默认空间");
        }
        Integer spaceLevel = spaceAddRequest.getSpaceLevel();
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(spaceLevel);
        if(spaceLevelEnum == null){
            spaceAddRequest.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
        }
        if(spaceAddRequest.getSpaceType() == null){
            spaceAddRequest.setSpaceType(SpaceTypeEnum.PRIVATE.getValue());
        }
        // 转换
        Space space = new Space();
        BeanUtil.copyProperties(spaceAddRequest, space);
        this.fillSpaceBySpaceLevel(space);
        Long userId = loginUser.getId();
        space.setUserId(userId);
        //2.校验参数
        space.validSpace(true);
        //3.校验权限，非管理员只能创建普通级别的空间
        if(SpaceLevelEnum.COMMON.getValue() != spaceLevel && !loginUser.isAdmin()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"无权限创建指定级别空间");
        }
        //4.控制同一用户只能创建一个私有空间
        //针对同一用户加锁
        Object lock = lockMap.computeIfAbsent(userId, key -> new Object());
        synchronized (lock) {
            try{
                //编程式事务
                Long newSpaceId = transactionTemplate.execute(status -> {
                    boolean exists = this.lambdaQuery()
                            .eq(Space::getUserId, userId)
                            .eq(Space::getSpaceType, spaceAddRequest.getSpaceType())
                            .exists();
                    ThrowUtils.throwIf(exists, ErrorCode.OPERATION_ERROR, "每个用户每类空间仅能拥有一个");
                    //创建空间
                    boolean save = this.save(space);
                    ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR, "添加空间失败");
                    // 如果是团队空间，关联新增团队成员记录
                    if (SpaceTypeEnum.TEAM.getValue() == spaceAddRequest.getSpaceType()) {
                        SpaceUser spaceUser = new SpaceUser();
                        spaceUser.setSpaceId(space.getId());
                        spaceUser.setUserId(userId);
                        spaceUser.setSpaceRole(SpaceRoleEnum.ADMIN.getValue());
                        save = spaceUserApplicationService.save(spaceUser);
                        ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR, "创建团队成员记录失败");
                    }
                    //关闭分库分表
//                    // 创建分表
//                    dynamicShardingManager.createSpacePictureTable(space);
                    return space.getId();
                });
                return Optional.ofNullable(newSpaceId).orElse(-1L);
            }finally {
                lockMap.remove(userId);
            }
        }
    }

    @Override
    public void checkSpaceAuth(User loginUser, Space space) {
        spaceDomainService.checkSpaceAuth(loginUser, space);
    }


}




